package com.pig4cloud.pig.module.controller.vip;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.splitAccount.SplitAccount;
import com.pig4cloud.pig.module.api.entity.vip.VipInfo;
import com.pig4cloud.pig.module.api.entity.vip.VipOrder;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.splitAccount.ISplitAccountService;
import com.pig4cloud.pig.module.service.vip.IVipInfoService;
import com.pig4cloud.pig.module.service.vip.IVipOrderService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 套餐活动支付订单Controller
 *
 * @author ruoyi
 * @date 2022-10-20
 */
@Validated
@Api(value = "套餐活动支付订单控制器", tags = {"套餐活动支付订单管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/vipOrder")
public class VipOrderController {

    private final IVipOrderService vipOrderService;
    private final IWxUserService wxUserService;
    private final IEstateService estateService;
    private final IVipInfoService vipInfoService;
	private final ISplitAccountService splitAccountService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;


    /**
     * 查询套餐活动支付订单列表
     */
    @ApiOperation("查询套餐活动支付订单列表")
    @PreAuthorize("@pms.hasPermission('module:vipOrder:list')")
    @GetMapping("/list")
    public TableDataInfo<VipOrder> list(@Validated VipOrder vipOrder) {
        QueryWrapper<VipOrder> qw = new QueryWrapper<>();
        if(vipOrder.getOrderNo()!=null){
            qw.eq("order_no",vipOrder.getOrderNo());
        }
        if(vipOrder.getNickName()!=null){
            qw.like("nick_name",vipOrder.getNickName());
        }
        if(vipOrder.getStatus()!=null){
            qw.eq("status",vipOrder.getStatus());
        }

		if(StrUtil.isNotEmpty(vipOrder.getBeginDate())){
			qw.between("create_time",vipOrder.getBeginDate() + " 00:00:00",vipOrder.getEndDate() + " 23:59:59");
		}


        qw.orderByDesc("create_time");
        TableDataInfo<VipOrder> td = PageUtils.buildDataInfo(vipOrderService.page(PageUtils.buildPage(),qw));
        List<VipOrder> list = td.getData();
        for (VipOrder list1 : list){
			if(list1.getEstateId() != null && list1.getEstateId() != 0){
				Estate estate = estateService.findById(list1.getEstateId());
				if(estate!=null){
					list1.setEstateName(estate.getEstateName());
				}
			}
            WxUser wxUser = wxUserService.findById(list1.getUserId());
            if(wxUser!=null){
				list1.setFaceUrl(wxUser.getFaceUrl());
				if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && !wxUser.getFaceUrl().contains("http")){
					list1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
				}
			}
            VipInfo vipInfo=vipInfoService.findById(list1.getVipInfoId());
            if(vipInfo != null){
				list1.setVipName(vipInfo.getVipTitle());
			}
        }

        return td;
    }

    /**
     * 导出套餐活动支付订单列表
     */
    @ApiOperation("导出套餐活动支付订单列表")
    @PreAuthorize("@pms.hasPermission('module:vipOrder:export')")
    @SysLog("套餐活动支付订单")
    @GetMapping("/export")
    public List export(@Validated VipOrder vipOrder) {
        List<VipOrder> list = vipOrderService.list();
        // ExcelUtil<VipOrder> util = new // ExcelUtil<VipOrder>(VipOrder.class);
        return list;// util.exportExcel(list, "套餐活动支付订单");
    }

    /**
     * 获取套餐活动支付订单详细信息
     */
    @ApiOperation("获取套餐活动支付订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:vipOrder:query')")
    @GetMapping("/{id}")
    public R<VipOrder> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") String id) {
        VipOrder vipOrder = vipOrderService.getById(id);
        if(vipOrder!=null){
			SplitAccount splitAccount = splitAccountService.getAccountByUserId(vipOrder.getUserId(),4,vipOrder.getUserId());
			if(splitAccount != null) {
				vipOrder.setVipMoney(splitAccount.getVipAccountMoney());
			}
		}
        return R.ok(vipOrder);
    }

    /**
     * 新增套餐活动支付订单
     */
    @ApiOperation("新增套餐活动支付订单")
    @PreAuthorize("@pms.hasPermission('module:vipOrder:add')")
    @SysLog("套餐活动支付订单")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody VipOrder vipOrder) {
        return R.okByRow(vipOrderService.save(vipOrder) ? 1 : 0);
    }

    /**
     * 修改套餐活动支付订单
     */
    @ApiOperation("修改套餐活动支付订单")
    @PreAuthorize("@pms.hasPermission('module:vipOrder:edit')")
    @SysLog("套餐活动支付订单")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody VipOrder vipOrder) {
        return R.okByRow(vipOrderService.updateById(vipOrder) ? 1 : 0);
    }


	/**
	 * 修改套餐活动支付订单
	 */
	@ApiOperation("修改套餐活动支付订单")
	@PreAuthorize("@pms.hasPermission('module:vipOrder:edit')")
	@SysLog("套餐活动支付订单")

	@PostMapping("/refund/order")
	public R<Void> refundOrder(@Valid @RequestBody VipOrder vipOrder) {
		boolean bl = false;
		if(vipOrder.getStatus() == 2 && (vipOrder.getRefundStatus() == 0 || vipOrder.getRefundStatus() == 1 || vipOrder.getRefundStatus() == 3)
			&& vipOrder.getRefundPrice().doubleValue() > 0){
			SplitAccount splitAccount = splitAccountService.getAccountByUserId(vipOrder.getUserId(),4,vipOrder.getUserId());
			if(splitAccount != null){
				double vipMoney = splitAccount.getVipAccountMoney().doubleValue();
				if(vipMoney >= vipOrder.getRefundPrice().doubleValue()){
					int ret = vipOrderService.refundOrder(vipOrder);
					if(ret > 0){
						bl = true;
					}
				}else{
					return R.failed("退款余额超过会员充值余额");
				}
			}else{
				return R.failed("该用户账号信息异常");
			}
 		}
		return R.okByRow(bl ? 1 : 0);
	}


	/**
	 * 订单退款查询
	 */
	@ApiOperation("订单退款查询")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:edit')")

	@GetMapping("/queryRefund/{id}")
	public R<Void> queryRefund(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
		VipOrder vipOrder = vipOrderService.getById(id);
		if(vipOrder!=null){
			int ret = vipOrderService.queryRefundOrder(vipOrder);
			if(ret > 0){
				return R.okByRow(1);
			}
		}
		return R.okByRow(0);
	}

    /**
     * 删除套餐活动支付订单
     */
    @ApiOperation("删除套餐活动支付订单")
    @PreAuthorize("@pms.hasPermission('module:vipOrder:remove')")
    @SysLog("套餐活动支付订单")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable String[] ids) {
        return R.okByRow(vipOrderService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
